package com.example.springconsuldemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import com.orbitz.consul.AgentClient;
import com.orbitz.consul.Consul;
import com.google.common.net.HostAndPort;
import com.orbitz.consul.model.agent.ImmutableRegistration;


@SpringBootApplication
public class DemoApplication {

	public static void main(String[] args) {
        // 启动嵌入式容器（如 Tomcat）
        SpringApplication.run(DemoApplication.class, args);
        
        // 服务注册
        Consul consul = Consul.builder()
                    .withHostAndPort(HostAndPort.fromString("11.11.1.100:8500"))
                    .build();
        final AgentClient agentClient = consul.agentClient();
        String service = "account_tomcat";
        String address = "11.11.1.101";
        String tag = "dev";
        Integer port = 8080;
        final String serviceId = address + ":" + port;
        ImmutableRegistration.Builder builder = ImmutableRegistration.builder();
        builder.id(serviceId).name(service)
               .address(address).port(port).addTags(tag);
        agentClient.register(builder.build());

        // JVM 停止时摘除服务
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                agentClient.deregister(serviceId);
            }
        });
	}

}
